/* ReMeMore-Moi
 * Code license: Apache License 2.0
 * WWW : http://code.google.com/p/rememore-moi/
 * */
package info.fredericb.rememoremoi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.Contacts.Intents.Insert;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class RememoremoiService extends Service {

	private Resources lRes;
	private static int NEWNUMBER_NOTIFICATION_ID = 1;
	public static String TAG = "Rememore-moi";

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		if (intent != null) {
			if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent
					.getAction())) {
				this.lRes = getResources();

				final String number = intent.getExtras().getString(
						"incoming_number");
				if (number != null) {
					String msg = String.format(lRes.getString(R.string.lookup_toast), number);
					Context ctx = getApplicationContext();
					Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();

					new WebParserTask(ctx, number).execute();
				}
			}
		} else
			Log.d(TAG, "Error: couldn't start RememoremoiService without valid Intent!");
		stopSelf();
	}
	
	private final class WebParserTask extends AsyncTask<Void, Void, String> {
		
		final private static String USER_AGENT = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16" ;
	    final private static String REGEX_PATTERN = "<div class=\"info\">[^<]*<h3>([^<]*)</h3>[^<]*<p class=\"location\">([^<]*)</p>";
	    final private static String REQUEST_URL = "http://smartphone.pagesjaunes.fr/smart/rechercheInverse.do?numero=%s";
	    
		private ContactInfo mWp;
		private Context ctx;
		
		public WebParserTask(Context mContext, String nb){
			this.ctx = mContext;
			this.mWp = new ContactInfo(nb);
		}
		
		@Override
		protected String doInBackground(Void... params) {
	        StringBuffer ret = new StringBuffer();
	        String url = String.format(REQUEST_URL, mWp.getLocalNumber());
	        try {
	            URL uri = new URL(url);
	            URLConnection urlc = uri.openConnection();
	            urlc.setRequestProperty("User-Agent", USER_AGENT);
	            InputStream is = urlc.getInputStream();
	            String tmp;
	            BufferedReader br = new BufferedReader(new InputStreamReader(is));
	            while ((tmp = br.readLine()) != null) {
	                ret.append(tmp);
	            }
	        } catch (MalformedURLException e) {
	            Log.d(TAG, e.getMessage());
	        } catch (IOException e) {
	        	Log.d(TAG, e.getMessage());
	        }
	        return ret.toString();
		}
		
		@Override
		protected void onPostExecute(String result) {
	        Pattern pattern = Pattern.compile(REGEX_PATTERN);
	        Matcher m = pattern.matcher(result);
	        if(m.find()){
	        	mWp.setRaison(m.group(1).trim());
	        	mWp.setAdresse(m.group(2).trim());
	        }
			onWebParserDone();
		}
		
		private void onWebParserDone() {
			if (mWp != null) {
				String raison = mWp.getRaison();
				if (raison != null) {
					Toast.makeText(ctx, raison, Toast.LENGTH_LONG).show();
					Toast.makeText(ctx, raison, Toast.LENGTH_LONG).show();
					Toast.makeText(ctx, raison, Toast.LENGTH_LONG).show();
					Toast.makeText(ctx, raison, Toast.LENGTH_LONG).show();
					Toast.makeText(ctx, raison, Toast.LENGTH_LONG).show();
					this.newNumberNotification(mWp);
				} else {
					Toast.makeText(ctx,
							lRes.getString(R.string.failed_toast),
							Toast.LENGTH_LONG).show();
				}
			}
			stopSelf();
		}
		
		private void newNumberNotification(ContactInfo wp) {
			int icon = R.drawable.icon_notification;
			CharSequence tickerText = lRes.getText(R.string.notif_newnum_ticker);
			long when = System.currentTimeMillis();
			Context context = getApplicationContext();
			CharSequence contentTitle = lRes.getString(R.string.notif_newnum_title);
			String msg = String.format(lRes.getString(R.string.notif_newnum_msg),
					wp.getNumber());
			CharSequence contentText = msg;
		
			Intent notificationIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
			notificationIntent.setType(ContactAccessor.getInstance()
					.getContentItemType());
			notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
			notificationIntent.putExtra(Insert.PHONE, wp.getNumber());
			notificationIntent.putExtra(Insert.NAME, wp.getRaison());
			notificationIntent.putExtra(Insert.POSTAL, wp.getAdresse());
			PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
					notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		
			// the next two lines initialize the Notification, using the
			// configurations above
			Notification notification = new Notification(icon, tickerText, when);
			notification.setLatestEventInfo(context, contentTitle, contentText,
					contentIntent);
			notification.flags |= Notification.FLAG_AUTO_CANCEL;
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
			mNotificationManager.notify(NEWNUMBER_NOTIFICATION_ID, notification);
		}
	}
}
